#pragma once

#include <iostream>
#include <string>
#include "TcpServer.hpp"
#include "InetAddr.hpp"

using namespace TcpServerModule;

const std::string Sep = "\r\n";
const std::string BlankLine = Sep;

class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }
    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client){ 
            return this->HandlerHttpRequest(sockfd, client); 
        });
        _tsvr->Loop();
    }
    // 就是我们处理http的入口
    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        std::cout << http_request; //字节流的请求

        // 读取请求，对请求进行分析处理 --> 文本处理！
        // 1. 读取请求的完整性 --- 暂时先不管这个
        // 2. 完整 http 进行反序列化，http response 做序列化...
        // Demo 1 : 直接返回一个固定的内容
        std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine; // 现在主流http 协议用的是 http/1.1

        // 直接返回一个html网页
        std::string body = "<!DOCTYPE html>\
                            <html>\
                           <head>\
                           <meta charset = \"UTF-8\">\
                           <title> Hello World</title>\
                           </head>\
                           <body>\
                           <p> Hello World</p>\
                           </body> </html>";
        
        std::string http_response = status_line + body;
        sockfd->Send(http_response);
        
        return true;
    }
    ~HttpServer() {}

private:
    std::unique_ptr<TcpServer> _tsvr;
};